package org.summerframework.web.error;

import org.springframework.stereotype.Controller;
import org.summerframework.core.base.result.DefaultResultCode;
import org.summerframework.core.base.result.ResultDTO;
import org.summerframework.core.util.UrlUtil;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 石超
 * @version v1.0.0
 */
@Controller
public class BasicErrorController implements ErrorController {

    @RequestMapping(value = {"/error", "/error/4xx", "/error5xx"})
    public String login(Model model, HttpServletRequest request) {
        model.addAttribute("result", ResultDTO.error(DefaultResultCode.getInstance(getStatus(request).value())));
        model.addAttribute("urlUtil", UrlUtil.getUrl());

        return "exception/htmlErr";
    }

    @Override
    public String getErrorPath() {
        return null;
    }

    protected HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        } catch (Exception ex) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }
}
